from core.exception.errors import ErrorException
from core.security import verify_password, create_access_token, get_password_hash
from crud.admin_cruds.user_crud import curd_admin_user
from models import AdminUser
from schemas.admin_schemas.admin_schema import Token, AdminUserCreate, AdminUserUpdate
from services.base_service import BaseService


class AdminService(BaseService):

    async def do_login(self, request, username: str, password: str) -> Token:
        """
        处理后台管理登录逻辑
        :param request:
        :param username:账号
        :param password:密码
        :return:
        """
        user = await curd_admin_user.get_row(key="username", value=username)
        if not user:
            # 用户不存在
            raise ErrorException('用户不存在')
        if user.is_active == 0:
            raise ErrorException('用户被禁用')
        if not verify_password(password, user.hashed_password):
            raise ErrorException('密码不正确')
        token_data = {
            "user_id": user.id
        }
        access_token, expire_timestamp = create_access_token(data=token_data, return_expire_timestamp=True)
        return Token(token=access_token, username=user.username, avatar=user.avatar, failure_time=expire_timestamp)

    async def create_admin_user(self, admin_user: AdminUserCreate) -> AdminUser:
        """
        创建管理员
        :param admin_user:
        """
        user = await curd_admin_user.get_row(key="username", value=admin_user.username)
        if user:
            raise ErrorException("管理员已存在")
        admin_user_obj = await curd_admin_user.create_admin_user(obj_in=admin_user)
        return admin_user_obj

    async def edit_admin_user(self, admin_user: AdminUserUpdate) -> AdminUser:
        """
        编辑管理员
        :param admin_user:
        """
        user = await curd_admin_user.get_row(key="id", value=admin_user.id)
        if user.username != admin_user.username:
            raise ErrorException("不能修改用户名")
        if not user:
            raise ErrorException("管理员不存在")
        admin_user_obj = await curd_admin_user.update_admin_user(obj_current=user, obj_new=admin_user)
        return admin_user_obj
